/*
 * @Author: Shane
 * @Date: 2022-07-06 17:13:21
 * @LastEditTime: 2022-07-13 10:39:06
 * @LastEditors: Shane
 * @Description: 
 * @FilePath: /app-framework/common_widgets/lib/text/highlight_text_widget2.dart
 */
/*
 * @author[hansen]
 * @date[创建日期: 2022/7/1 9:01]
 * @version[版本: v1.0]
 * @function[功能简介: 高亮显示的widget]
 */

import 'package:flutter/material.dart';

class HighlightTextWidget2 extends StatelessWidget {
  ///文本
  final String text;

  ///高亮文本
  final String lightText;

  ///文本style
  final TextStyle textStyle;

  ///高亮文本style
  final TextStyle lightTextStyle;
  final int? maxLines;
  final TextOverflow overflow;
  final TextAlign textAlign;

  const HighlightTextWidget2({
    Key? key,
    required this.text,
    required this.lightText,
    this.maxLines,
    this.overflow = TextOverflow.clip,
    this.textAlign = TextAlign.start,
    this.textStyle = const TextStyle(
      color: Color(0xff333333),
      fontSize: 14,
    ),
    this.lightTextStyle = const TextStyle(
      color: Color(0xffC20014),
      fontSize: 14,
    ),
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (lightText.isEmpty) {
      return Text(
        text,
        style: textStyle,
      );
    }
    return RichText(
      maxLines: maxLines,
      overflow: overflow,
      textAlign: textAlign,
      text: TextSpan(
        style: textStyle,
        children: getTextSpan(),
      ),
    );
  }

  List<TextSpan> getTextSpan() {
    List<String> arr = lightText.split(" ");

    String pattern = r"";
    arr.sort((a, b) => b.length.compareTo(a.length));
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].trim().isEmpty) continue;
      pattern += arr[i];
      if (i != arr.length - 1) {
        pattern += "|";
      }
    }
    print(pattern);
    String sources = text;
    Iterable<Match> matches =
        RegExp(pattern, caseSensitive: false).allMatches(sources);
    List<TextSpan> result = [];
    int start = 0;
    for (var match in matches) {
      result.add(TextSpan(text: sources.substring(start, match.start)));
      var text = sources.substring(match.start, match.end);
      result.add(
        TextSpan(
          text: text,
          style: lightTextStyle,
        ),
      );
      start = match.end;
    }
    result.add(TextSpan(text: sources.substring(start)));
    return result;
  }
}
